<?php
/**
 * Description of Captcha
 *
 * @author FFOZEU
 */
namespace Library\Classe\Form;

class FormCaptcha extends FormInput{
    
		/* Characters available in images */
		protected $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';

		/* Length of a word in an image */
		protected $char_length = 4;

		/* Array of fonts. Randomly picked up per character */
		protected $fonts = array();

		/* Directory temporary keeping CAPTCHA images and corresponding codes */
		protected $tmp_dir = '';

		/* Array of CAPTCHA image size. Width and height */
		protected $img_size = array( 72, 24 );

		/* Background color of CAPTCHA image. RGB color 0-255 */
		protected $bg = array( 255,255, 255 );

		/* Foreground (character) color of CAPTCHA image. RGB color 0-255 */
		protected $fg = array( 0, 0, 0 );

		/* Coordinates for a text in an image. I don't know the meaning. Just adjust. */
		protected $base = array( 6, 18 );

		/* Font size */
		protected $font_size = 14;

		/* Width of a character */
		protected $font_char_width = 15;

		/* Image type. 'png', 'gif' or 'jpeg' */
		protected $img_type = 'png';
        
        //nom de l'images
        protected $imgCaptcha ="";
        
        /* Mode of temporary files */
		protected $file_mode = 0755;
        
    public function __construct($name, $form) {

		parent::__construct($name, $form);
		$this->attrs['type'] = 'captcha';
        $this->fonts = array(
			dirname( __FILE__ ) . '/Captcha/gentium/GenAI102.TTF',
			dirname( __FILE__ ) . '/Captcha/gentium/GenAR102.TTF',
			dirname( __FILE__ ) . '/Captcha/gentium/GenI102.TTF',
			dirname( __FILE__ ) . '/Captcha/gentium/GenR102.TTF' );
        
        $this->tmp_dir = _SITE_UPLOAD_DIR_. 'captcha/';
	}
    
    protected function _init() {

		if (!isset(self::$error_list['incorrect_code'])) {

			self::$error_list['incorrect_code'] = "Le Code saisie est incorret.";
		}
	}
    
    public function is_valid($value) {

		if (parent::is_valid($value)) {
            
            $control_captcha =$this->verif_captcha($_POST);
			if ($control_captcha != $value) {
               
				$this->_error('incorrect_code');
				return false;
			}
			return true;
		}
		return false;
	}
    
    public function __toString() {

		$tab = func_num_args() > 0 ? func_get_arg(0) : '';
		
		$this->_generate_class();

		$id = '';
		$label = '';
        //generation du captcha
        $word = $this->generate_random_word();
        $prefix = mt_rand();
        $this->generate_image( $prefix, $word );
        
		if (!empty($this->label)) {

			list($for, $id) = self::_generate_for_id($this->form->auto_id(), $this->attrs['name']);
			$label = '<label'.$for.'>'.$this->label.$this->form->label_suffix().'</label>'."\n$tab";
		}

		$errors = $this->error_messages->__toString($tab);
		if (!empty($errors)) { $errors = "\n".$errors; }

		$field = '<input'.$id.$this->attrs.' />
                <input type="hidden" value="'.substr($this->imgCaptcha, 0, -4).'" name="token_captcha"/>
                <img src="'._UPLOAD_DIR_.'captcha/'.$this->imgCaptcha.'" class="captcha" alt="captcha" style="vertical-align: middle;"/>';
		return $tab.sprintf("%2\$s%1\$s%3\$s", $field, $label, $errors);
	}

	/* Generate and return random word with $chars characters x $char_length length */

	function generate_random_word() {
		$word = '';
		for ( $i = 0; $i < $this->char_length; $i++ ) {
			$pos = mt_rand( 0, strlen( $this->chars ) - 1 );
			$char = $this->chars[$pos];
			$word .= $char;
		}
		return $word;
	}

	/* Generate CAPTCHA code and corresponding code and save them into $tmp_dir directory.
	$prefix is file prefix for both files.
	$captcha is a random word usually generated by generate_random_word()
	This function returns the filename of the CAPTCHA image temporary file */

	function generate_image( $prefix, $word ) {
		$dir = $this->trailingslashit( $this->tmp_dir );
		$filename = null;
        $dateheure = strftime("%d%m%y_%H%M%S");
		if ( $im = imagecreatetruecolor( $this->img_size[0], $this->img_size[1] ) ) {
			$bg = imagecolorallocate( $im, $this->bg[0], $this->bg[1], $this->bg[2] );
			$fg = imagecolorallocate( $im, $this->fg[0], $this->fg[1], $this->fg[2] );

			imagefill( $im, 0, 0, $bg );

			$x = $this->base[0] + mt_rand( -2, 2 );

			for ( $i = 0; $i < strlen( $word ); $i++ ) {
				$font = $this->fonts[array_rand( $this->fonts )];
				imagettftext( $im, $this->font_size, mt_rand( -2, 2 ), $x,
					$this->base[1] + mt_rand( -2, 2 ), $fg, $font, $word[$i] );
				$x += $this->font_char_width;
			}

			switch ( $this->img_type ) {
				case 'jpeg':
					$filename = $dateheure.$prefix . '.jpeg';
					imagejpeg( $im, $dir . $filename );
					break;
				case 'gif':
					$filename = $dateheure.$prefix . '.gif';
					imagegif( $im, $dir . $filename );
					break;
				case 'png':
				default:
					$filename = $dateheure.$prefix . '.png';
					imagepng( $im, $dir . $filename );
			}
            
            $this->imgCaptcha = $filename;
            
			imagedestroy( $im );
			@chmod( $dir . $filename, $this->file_mode );
		}

		$answer_file = $dir . $dateheure.$prefix . '.php';

		if ( $fh = fopen( $answer_file, 'w' ) ) {
			@chmod( $answer_file, $this->file_mode );
			fwrite( $fh, $word);
			fclose( $fh );
		}

		return $filename;
	}
    
    public function verif_captcha(array $param){
        $out='';
        if ( $fh = fopen($this->tmp_dir.$param['token_captcha'].'.php', 'r' ) ) {
			@chmod( $answer_file, $this->file_mode );
			$out = fread( $fh, $this->char_length);
			fclose( $fh );
		}
        return $out;
    }
    /* Check a $response against the code kept in the temporary file with $prefix
	Return true if the two match, otherwise return false. */

	function check( $prefix, $response ) {
		$dir = $this->trailingslashit( $this->tmp_dir );
		$filename = sanitize_file_name( $prefix . '.php' );
		$file = $dir . $filename;

		if ( is_readable( $file ) ) {
			include( $file );
			if ( 0 == strcasecmp( $response, $captcha ) )
				return true;
		}
		return false;
	}

	/* Remove temporary files with $prefix */

	function remove( $prefix ) {
		$suffixes = array( '.jpeg', '.gif', '.png', '.php', '.txt' );

		foreach ( $suffixes as $suffix ) {
			$filename = sanitize_file_name( $prefix . $suffix );
			$file = trailingslashit( $this->tmp_dir ) . $filename;
			if ( is_file( $file ) )
				unlink( $file );
		}
	}

	/* Clean up dead files older than $minutes in the tmp folder */

	function cleanup( $minutes = 60 ) {
		$dir = trailingslashit( $this->tmp_dir );

		if ( ! is_dir( $dir ) || ! is_readable( $dir ) || ! is_writable( $dir ) )
			return false;

		$count = 0;

		if ( $handle = @opendir( $dir ) ) {
			while ( false !== ( $filename = readdir( $handle ) ) ) {
				if ( ! preg_match( '/^[0-9]+\.(php|txt|png|gif|jpeg)$/', $filename ) )
					continue;

				$file = $dir . $filename;

				$stat = @stat( $file );
				if ( ( $stat['mtime'] + $minutes * 60 ) < time() ) {
					@unlink( $file );
					$count += 1;
				}
			}

			closedir( $handle );
		}

		return $count;
	}
    
    /**
     * Appends a trailing slash.
     *
     * Will remove trailing slash if it exists already before adding a trailing
     * slash. This prevents double slashing a string or path.
     *
     * The primary use of this is for paths and thus should be used for paths. It is
     * not restricted to paths and offers no specific path support.
     *
     * @since 1.2.0
     * @uses untrailingslashit() Unslashes string if it was slashed already.
     *
     * @param string $string What to add the trailing slash to.
     * @return string String with trailing slash added.
     */
    function trailingslashit($string) {
        return $this->untrailingslashit($string) . '/';
    }
    
    /**
     * Removes trailing slash if it exists.
     *
     * The primary use of this is for paths and thus should be used for paths. It is
     * not restricted to paths and offers no specific path support.
     *
     * @since 2.2.0
     *
     * @param string $string What to remove the trailing slash from.
     * @return string String without the trailing slash.
     */
    function untrailingslashit($string) {
        return rtrim($string, '/');
    }

}

?>